/**
 * 作者：陈文斌 on 2019/1/3.
 * 邮箱：chen_wennbin@163.com
 * 版本：v1.0
 */

import 'package:flutter/material.dart';
import 'package:crm/tools/http_util.dart';
import 'package:crm/tools/apollo_util.dart';
import 'package:crm/tools/shared_preferences_util.dart';
import 'package:crm/tools/regex_util.dart';
import 'package:crm/view/Dialog/loading_dialog.dart';
import 'package:crm/model/main_scoped_model.dart';
import 'package:crm/constant/api.dart';
import 'dart:convert';

import 'package:crm/page/Login/crm_first_login_page.dart';
import 'package:crm/page/SettingPassword/crm_setting_gesture_password_page.dart';
import 'package:crm/page/Login/crm_login_page.dart';
import 'package:crm/page/ClientManager/crm_client_manager_page.dart';

class LoginVM {
  /// 登录
  login(BuildContext context, phone, pass) {
    // 验证手机号
//    if (!(RegexUtil.isMobileSimple(phone) || RegexUtil.isMobileExact(phone))) {
//      showDialog<bool>(
//        context: context,
//        builder: (BuildContext context) {
//          return AlertDialog(
//            content: const Text(
//              '请输入正确的手机号码',
//            ),
//            actions: <Widget>[
//              FlatButton(
//                child: const Text('确定'),
//                onPressed: () {
//                  Navigator.of(context).pop(true);
//                },
//              ),
//            ],
//          );
//        },
//      );
//      return;
//    }
    if (pass.length < 6) {
      // 验证密码
      showDialog<bool>(
        context: context,
        builder: (BuildContext context) {
          return AlertDialog(
            content: const Text(
              '请输入正确的密码',
            ),
            actions: <Widget>[
              FlatButton(
                child: const Text('确定'),
                onPressed: () {
                  Navigator.of(context).pop(true);
                },
              ),
            ],
          );
        },
      );
      return;
    }

    // 表单提交
    var api = 'http://devapi.fccn.cc/Api/v1.1/Account/Login';
    var data = {
      "Account": phone,
      "Password": pass,
      "RememberMe": "true",
      "LoginMethod": "P:Android,B:honor,BC:FRD-AL00,OS:EMUI,OSV:24,APPV:4.3.2",
      "PhoneRegionCode": "+86"
    };

    showDialog<bool>(
      context: context,
      builder: (BuildContext context) {
        return LoadingDialog(
          text: '登录……',
        );
      },
    );

    HttpUtil.post(
      api,
      (response) {
        Navigator.of(context).pop(true);
        SpUtil.putString('UserInfo', response.toString());
        SpUtil.putString('PhoneNumber', response['PhoneNumber']);
        SpUtil.putBool('isLogin', true);

        // 判断是否设置过密码
        ApolloRequestUtil.isInitPassword((response) {
          if (response["data"]["checkStatus"]["isInitPassword"]) {
            Navigator.push(
              context,
              MaterialPageRoute(builder: (context) => CRMLoginPage()),
            );
          } else {
            Navigator.push(
              context,
              new MaterialPageRoute(
                builder: (context) => FirstLoginPage(),
              ),
            );
          }
        }, errorCallback: (errMsg) {
          Navigator.push(
            context,
            new MaterialPageRoute(
              builder: (context) => FirstLoginPage(),
            ),
          );
        });
      },
      params: data,
      errorCallback: (errMsg) {
        Navigator.of(context).pop(true);
        showDialog<bool>(
          context: context,
          builder: (BuildContext context) {
            return AlertDialog(
              content: Text(
                errMsg,
              ),
              actions: <Widget>[
                FlatButton(
                  child: const Text('确定'),
                  onPressed: () {
                    Navigator.of(context).pop(true);
                  },
                ),
              ],
            );
          },
        );
      },
    );
  }

  /// CRM 设置密码
  crmSettingPassword(BuildContext context) {
    final loginScopedModel = MainModel().of(context);

    var args = {
      'passwordText': loginScopedModel.passwordText,
      'passwordGesture': loginScopedModel.passwordGesture,
    };

    showDialog<bool>(
      context: context,
      builder: (BuildContext context) {
        return LoadingDialog(
          text: '设置密码……',
        );
      },
    );

    ApolloRequestUtil.changePasswordQuery(
        (response) {
          // 请求成功
          Navigator.pop(context);
          // 请求失败
          showDialog<bool>(
            context: context,
            builder: (BuildContext context) {
              return SuccessDialog(
                text: '设置成功!',
              );
            },
          );

          SpUtil.putString("CrmUserInfo", jsonEncode(response));

          Future.delayed(const Duration(seconds: 3), () {
            Navigator.pop(context);
            Navigator.push(context,
                MaterialPageRoute(builder: (context) => CRMLoginPage()));
          });
        },
        args: args,
        errorCallback: (errMsg) {
          Navigator.pop(context);
          // 请求失败
          showDialog<bool>(
            context: context,
            builder: (BuildContext context) {
              return ErrorDialog(
                text: '设置失败!',
              );
            },
          );

          Future.delayed(
              const Duration(seconds: 3), () => Navigator.pop(context));
        });
  }

  goSettingPasswordText({
    @required BuildContext context,
    @required String firstPass,
    @required String secondPass,
  }) {
    if (firstPass == null || secondPass == null) {
      showDialog<bool>(
        context: context,
        builder: (BuildContext context) {
          return AlertDialog(
            content: const Text(
              '请输入完整密码！',
            ),
            actions: <Widget>[
              FlatButton(
                child: const Text('确定'),
                onPressed: () {
                  Navigator.of(context).pop(true);
                },
              ),
            ],
          );
        },
      );
      return;
    }

    if (firstPass != secondPass) {
      showDialog<bool>(
        context: context,
        builder: (BuildContext context) {
          return AlertDialog(
            content: const Text(
              '密码不一致，请重新输入！',
            ),
            actions: <Widget>[
              FlatButton(
                child: const Text('确定'),
                onPressed: () {
                  Navigator.of(context).pop(true);
                },
              ),
            ],
          );
        },
      );
      return;
    }

    if (firstPass.length < 6) {
      showDialog<bool>(
        context: context,
        builder: (BuildContext context) {
          return AlertDialog(
            content: const Text(
              '请输入正确的密码',
            ),
            actions: <Widget>[
              FlatButton(
                child: const Text('确定'),
                onPressed: () {
                  Navigator.of(context).pop(true);
                },
              ),
            ],
          );
        },
      );
      return;
    }

    final MainModel loginScopedModel = MainModel().of(context);
    loginScopedModel.changePasswordText(firstPass);

    Navigator.push(
      context,
      MaterialPageRoute(builder: (context) => SettingGesturePasswordPage()),
    );
  }

  /// CRM登录
  static void crmLogin(
      {BuildContext context, String password, int loginType, String smsCode}) {
    var data;
    switch (loginType) {
      case 1: // 文本密码
        {
          data = {
            'password': password,
            'loginType': '1',
          };
        }
        break;
      case 2: // 手势密码
        {
          data = {
            'password': password,
            'loginType': '2',
          };
        }
        break;
      case 3: // 验证码验证登录
        {
          data = {
            'loginType': '3',
            'smsCode': '132422',
          };
        }
        break;
    }
    showDialog<bool>(
      context: context,
      builder: (BuildContext context) {
        return LoadingDialog(
          text: '登录……',
        );
      },
    );

    HttpUtil.multipartFile(
      JavaApi.CRMLogin,
      (response) {
        if (response['code'] == 0) {
          // 登录成功
          Navigator.pop(context);
          Navigator.push(context,
              MaterialPageRoute(builder: (context) => ClientManagerPage()));
        } else {
          // 登录错误
          Navigator.pop(context);
          showDialog<bool>(
            context: context,
            builder: (BuildContext context) {
              return ErrorDialog(
                text: response['message'],
              );
            },
          );

          Future.delayed(
              const Duration(seconds: 3), () => Navigator.pop(context));
        }
      },
      params: data,
      errorCallback: (errMsg) {
        // 登录失败
        Navigator.pop(context);
      },
      isSaveCookie: false,
    );
  }

  /// 获取验证码
  sendSms(String verifyCode, String phone) {
    var args = {
      "verifyCode": verifyCode ?? '',
    };

    ApolloRequestUtil.sendSms(
        (response) {
          print('1111');
        },
        args: args,
        errorCallback: (errMsg) {
          print('222');
        });
  }

  goSettingPasswordGesture({
    @required BuildContext context,
    @required String gesturePass,
  }) {
    final MainModel loginScopedModel = MainModel().of(context);
    loginScopedModel.changePasswordGesture(gesturePass);

    crmSettingPassword(context);
  }
}
